package com.miragedev.mononara.gui;

import com.miragedev.mononara.core.service.MononaraService;
import org.apache.commons.logging.LogFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ResourceBundle;

public class SyncFrame extends JDialog {
    private JPanel contentPane;
    private JButton buttonCancel;
    private JProgressBar progressBarSync;
    private JLabel labelEntry;
    private JLabel labelTitle;
    private JLabel labelStatus;

    public SyncFrame(final MononaraService service) {
        /*
        service.getHandlerDictionnary().addDictionnaryEntryAddedListener(new DictionaryEntryAddedListener() {
            public void entryAdded(final DictionaryEntryAddedEvent event) {
                labelTitle.setText("Loading Dictionnary");
                progressBarSync.setMinimum(0);
                progressBarSync.setMaximum(event.getNumberOfEntry());
                progressBarSync.setValue(event.getEntryNumber());
                progressBarSync.setStringPainted(true);
                labelEntry.setText(String.format("%1$s : %2$s", event.getEntry().getSpellingInKanji(), event.getEntry().getSpellingInKana()));
                labelStatus.setText(String.format("%1$d/%2$d", event.getEntryNumber(), event.getNumberOfEntry()));
                repaint();
            }
        });

        service.getHandlerKanji().addKanjiAddedListener(new KanjiAddedListener() {
            public void kanjiAdded(final KanjiAddedEvent event) {
                labelTitle.setText("Loading Kanjis");
                progressBarSync.setMinimum(0);
                progressBarSync.setMaximum(event.getNumberOfEntry());
                progressBarSync.setValue(event.getEntryNumber());
                progressBarSync.setStringPainted(true);
                labelEntry.setText(String.format("%1$s", event.getKanji().getCharacter()));
                labelStatus.setText(String.format("%1$d/%2$d", event.getEntryNumber(), event.getNumberOfEntry()));
                repaint();
            }
        });
        */

        setContentPane(contentPane);
        setModal(true);
        setLocationRelativeTo(this.getParent());
        getRootPane().setDefaultButton(buttonCancel);

        addWindowFocusListener(new WindowAdapter() {
            public void windowGainedFocus(WindowEvent e) {
                LogFactory.getFactory().getInstance(SyncFrame.class).info("Window state changed : " + e.getNewState());
                try {
                    service.onlineSync();
                    /*SwingWorker worker = new SwingWorker<Integer, Void>() {
                        public Integer doInBackground() {

                            return null;
                        }

                        public void done() {
                            onCancel();
                        }

                    };
                    worker.execute();
                    */
                } finally {
                    onCancel();
                    LogFactory.getFactory().getInstance(SyncFrame.class).info("killing window : ");
                }
            }
        });

        buttonCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        });

// call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

// call onCancel() on ESCAPE
        contentPane.registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    }

    private void onCancel() {
// add your code here if necessary
        dispose();
    }

    {
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
        $$$setupUI$$$();
    }

    /**
     * Method generated by IntelliJ IDEA GUI Designer
     * >>> IMPORTANT!! <<<
     * DO NOT edit this method OR call it in your code!
     *
     * @noinspection ALL
     */
    private void $$$setupUI$$$() {
        contentPane = new JPanel();
        contentPane.setLayout(new GridBagLayout());
        final JPanel panel1 = new JPanel();
        panel1.setLayout(new GridBagLayout());
        GridBagConstraints gbc;
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.weightx = 1.0;
        gbc.fill = GridBagConstraints.BOTH;
        contentPane.add(panel1, gbc);
        final JPanel panel2 = new JPanel();
        panel2.setLayout(new GridBagLayout());
        gbc = new GridBagConstraints();
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.weighty = 1.0;
        gbc.fill = GridBagConstraints.BOTH;
        panel1.add(panel2, gbc);
        buttonCancel = new JButton();
        this.$$$loadButtonText$$$(buttonCancel, ResourceBundle.getBundle("InterfaceResources").getString("syncframe.button.cancel"));
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(5, 0, 5, 0);
        panel2.add(buttonCancel, gbc);
        final JPanel panel3 = new JPanel();
        panel3.setLayout(new GridBagLayout());
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        gbc.fill = GridBagConstraints.BOTH;
        contentPane.add(panel3, gbc);
        progressBarSync = new JProgressBar();
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.gridwidth = 2;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(0, 10, 0, 10);
        panel3.add(progressBarSync, gbc);
        labelEntry = new JLabel();
        this.$$$loadLabelText$$$(labelEntry, ResourceBundle.getBundle("InterfaceResources").getString("syncframe.label.entry"));
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.weightx = 0.75;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(0, 10, 10, 10);
        panel3.add(labelEntry, gbc);
        labelTitle = new JLabel();
        labelTitle.setFont(new Font(labelTitle.getFont().getName(), labelTitle.getFont().getStyle(), 20));
        labelTitle.setHorizontalAlignment(0);
        labelTitle.setHorizontalTextPosition(10);
        this.$$$loadLabelText$$$(labelTitle, ResourceBundle.getBundle("InterfaceResources").getString("syncframe.label.title"));
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        gbc.weightx = 1.0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(10, 10, 50, 10);
        panel3.add(labelTitle, gbc);
        labelStatus = new JLabel();
        this.$$$loadLabelText$$$(labelStatus, ResourceBundle.getBundle("InterfaceResources").getString("syncframe.label.status"));
        gbc = new GridBagConstraints();
        gbc.gridx = 1;
        gbc.gridy = 2;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.insets = new Insets(0, 0, 10, 10);
        panel3.add(labelStatus, gbc);
    }

    /**
     * @noinspection ALL
     */
    private void $$$loadLabelText$$$(JLabel component, String text) {
        StringBuffer result = new StringBuffer();
        boolean haveMnemonic = false;
        char mnemonic = '\0';
        int mnemonicIndex = -1;
        for (int i = 0; i < text.length(); i++) {
            if (text.charAt(i) == '&') {
                i++;
                if (i == text.length()) break;
                if (!haveMnemonic && text.charAt(i) != '&') {
                    haveMnemonic = true;
                    mnemonic = text.charAt(i);
                    mnemonicIndex = result.length();
                }
            }
            result.append(text.charAt(i));
        }
        component.setText(result.toString());
        if (haveMnemonic) {
            component.setDisplayedMnemonic(mnemonic);
            component.setDisplayedMnemonicIndex(mnemonicIndex);
        }
    }

    /**
     * @noinspection ALL
     */
    private void $$$loadButtonText$$$(AbstractButton component, String text) {
        StringBuffer result = new StringBuffer();
        boolean haveMnemonic = false;
        char mnemonic = '\0';
        int mnemonicIndex = -1;
        for (int i = 0; i < text.length(); i++) {
            if (text.charAt(i) == '&') {
                i++;
                if (i == text.length()) break;
                if (!haveMnemonic && text.charAt(i) != '&') {
                    haveMnemonic = true;
                    mnemonic = text.charAt(i);
                    mnemonicIndex = result.length();
                }
            }
            result.append(text.charAt(i));
        }
        component.setText(result.toString());
        if (haveMnemonic) {
            component.setMnemonic(mnemonic);
            component.setDisplayedMnemonicIndex(mnemonicIndex);
        }
    }

    /**
     * @noinspection ALL
     */
    public JComponent $$$getRootComponent$$$() {
        return contentPane;
    }
}
